import json


def reformat(json_line):
    jsonObject = json.loads(json_line)
    s_id = jsonObject.get("id")
    jsonObject["uid"] = "_:" + s_id
    s_authors = jsonObject.get("authors")
    for author in s_authors:
        ids = author.get("ids")
        if len(ids) > 0:
            author["uid"] = "_:" + ids[0]
        else:
            author["uid"] = "_:anonymity"
    s_outCitations = jsonObject.get("outCitations")
    outCitations = []
    for outcitation in s_outCitations:
        a = {"id": "_:" + outcitation, "uid": "_:" + outcitation}
        outCitations.append(a)
    jsonObject["outCitations"] = outCitations
    s_inCitations = jsonObject.get("inCitations")
    inCitations = []
    for incitation in s_inCitations:
        a = {"id": "_:" + incitation, "uid": "_:" + incitation}
        inCitations.append(a)
    jsonObject["inCitations"] = inCitations

    # 间接修改字段名称
    jsonObject["authoris"] = jsonObject.pop("authors")
    jsonObject["incitationis"] = jsonObject.pop("inCitations")
    jsonObject["outcitationis"] = jsonObject.pop("outCitations")
    new_json = json.dumps(jsonObject)
    return new_json


path = "D:/java_projects/dgraph_import/src/main/resources/100.json"
format_data = "D:/java_projects/dgraph_import/src/main/resources/100format.json"


def read_write_file(path_a, f_a):
    f2 = open(f_a, 'w', encoding='utf-8')
    i = 0
    with open(path_a, 'r', encoding='utf-8') as f1:
        for line in f1:
            i += 1
            # if i % 1000 == 0:
            #     print("执行到了第%d条" % i)
            f2.write(reformat(line) + ",\n")


if __name__ == '__main__':
    read_write_file(path, format_data)
